<template>
	<view class="wrap">
		<view class="subwrap">
			<uv-form ref="uvForm" :model="item" :rules="rules" :borderBottom="false" labelWidth="auto" labelPosition="top" :labelStyle="labelStyle" errorType="toast">
				<uv-form-item label="发布类型" prop="type" :customStyle="{ padding: 0 }">
					<uv-subsection :list="$mData.types" :current="item.type - 1" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="typeSectionChange" />
				</uv-form-item>
				
				<uv-gap :height="10" />
				
				<uv-divider :text="`${$mData.types[item.type-1].name}：${$mData.types[item.type-1].tips}`"></uv-divider>
				
				<uv-form-item :label="$mData.types[item.type-1].name + '标题'" prop="title">
					<uv-input v-model="item.title" trim placeholder="请输入" />
				</uv-form-item>

				<uv-form-item label="宠物视频（可选项）" prop="video">
					<uv-upload :fileList="fileListVideo" name="Video" accept="video" :maxCount="1" :maxSize="100 * 1024 * 1024" @afterRead="afterRead" @delete="trash"></uv-upload>
				</uv-form-item>
				
				<uv-form-item label="宠物图片（1-6张）" prop="images">
					<uv-upload :fileList="fileListImage" name="Image" accept="image" previewFullImage previewImage multiple :maxCount="6" :maxSize="5 * 1024 * 1024" @afterRead="afterRead" @delete="trash"></uv-upload>
				</uv-form-item>

				<uv-form-item label="宠物分类" prop="cate">
					<uv-subsection :list="$mData.cates" :current="item.cate - 1" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="cateSectionChange" />
				</uv-form-item>
				
				<uv-form-item label="宠物性别" prop="gender">
					<uv-subsection :list="$mData.genders" :current="item.gender" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="genderSectionChange" />
				</uv-form-item>
				
				<uv-form-item label="宠物年龄" prop="age">
					<uv-subsection :list="$mData.ages" :current="item.age - 1" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="ageSectionChange" />
				</uv-form-item>

				<template v-if="item.type != 3">
					<uv-form-item label="宠物昵称" prop="nickname">
						<uv-input v-model="item.nickname" trim placeholder="请输入" />
					</uv-form-item>
				</template>

				<uv-form-item label="宠物品种" prop="breed">
					<uv-input v-model="item.breed" trim placeholder="请输入" />
				</uv-form-item>
				
				<template v-if="item.type == 1">
					<uv-form-item label="有偿无偿" prop="mode">
						<uv-subsection :list="$mData.modes" :current="item.mode" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="modeSectionChange" />
					</uv-form-item>
				</template>
				
				<template v-if="(item.type == 1 && item.mode > 0) || item.type == 2">
					<uv-form-item label="金额" prop="money" right-icon="red-packet-fill">
						<uv-input type="digit" v-model="item.money" trim placeholder="请输入金额" />
					</uv-form-item>
				</template>
				
				<uv-divider text="领养红包：领养人支付红包不超过200元"v-if="item.type == 1 && item.mode == 1"></uv-divider>
				
				<uv-divider text="领养押金：领养人支付不超过2000元，平台保管" v-if="item.type == 1 && item.mode == 2"></uv-divider>
				
				<uv-divider text="寻宠悬赏：发布人支付悬赏红包不超过10000元" v-if="item.type == 2"></uv-divider>
				
				<template v-if="item.type == 1 && item.mode == 2">
					<uv-gap :height="10" />

					<uv-form-item label="押金退还条件" prop="refund_condition">
						<uv-textarea v-model="item.refund_condition" :height="40" :customStyle="customStyle01" placeholder="请输入" />
					</uv-form-item>
				</template>
				
				<template v-if="item.type == 1">
					<uv-form-item label="宠物现状" prop="vaccine">
						<uv-subsection :list="$mData.vaccines" :current="item.vaccine" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="vaccineSectionChange" />
					</uv-form-item>
					
					<uv-form-item prop="sterilize">
						<uv-subsection :list="$mData.sterilizes" :current="item.sterilize" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="sterilizeSectionChange" />
					</uv-form-item>
					
					<uv-form-item prop="deworm">
						<uv-subsection :list="$mData.deworms" :current="item.deworm" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="dewormSectionChange" />
					</uv-form-item>
					
					<uv-form-item prop="source">
						<uv-subsection :list="$mData.sources" :current="item.source - 1" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="sourceSectionChange" />
					</uv-form-item>
					
					<uv-form-item prop="size">
						<uv-subsection :list="$mData.sizes" :current="item.size - 1" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="sizeSectionChange" />
					</uv-form-item>
					
					<uv-form-item prop="hair">
						<uv-subsection :list="$mData.hairs" :current="item.hair - 1" mode="button" :height="34" :bold="false" inactiveColor="#FFF" activeColor="#333" :bgColor="themeColor.color" @change="hairSectionChange" />
					</uv-form-item>
					
					<uv-form-item label="宠物特点" prop="tags">
						<uv-checkbox-group @change="tagsCheckboxGroupChange">
							<uv-checkbox @change="tagsCheckboxChange" :labelDisabled="false" :labelSize="12" :activeColor="themeColor.color" v-model="tag.checked" v-for="(tag, index) in $mData.tags" :key="index" :name="tag.name" :label="tag.name" :customStyle="{ width: '50%' }" />
						</uv-checkbox-group>
					</uv-form-item>
					
					<uv-form-item label="领养要求" prop="requirements">
						<uv-checkbox-group @change="requirementsCheckboxGroupChange">
							<uv-checkbox @change="requirementsCheckboxChange" :labelSize="12" :activeColor="themeColor.color" v-model="requirement.checked" v-for="(requirement, index) in $mData.requirements" :key="index" :name="requirement.name" :label="requirement.name" :customStyle="{ width: '50%' }" />
						</uv-checkbox-group>
					</uv-form-item>
					
					<uv-form-item label="其他要求" prop="other_requirement">
						<uv-textarea v-model="item.other_requirement" :height="40" :customStyle="customStyle01" placeholder="如有其它要求请输入（选填）" />
					</uv-form-item>
				</template>
								
				<template v-if="item.type != 1">
					<uv-form-item :label="$mData.types[item.type-1].title + '时间'" prop="datetime_name">
						<uv-input v-model="item.datetime_name" placeholder="请选择" suffixIcon="clock" @focus="datetimePickerShow" />
					</uv-form-item>
				</template>
				
				<uv-form-item :label="$mData.types[item.type-1].title + '地点'" prop="address">
					<uv-input v-model="item.address" placeholder="请选择" suffixIcon="map" @focus="chooseLocation" />
				</uv-form-item>
				
				<uv-form-item :label="$mData.types[item.type-1].content" prop="content">
					<uv-textarea v-model="item.content" :height="100" autoHeight :maxlength="99999" count :customStyle="customStyle01" placeholder="请尽量详细介绍" />
				</uv-form-item>
				
				<uv-form-item label="联系方式"></uv-form-item>
				
				<view class="contact">
					<uv-form-item prop="member.nickname">
						<uv-input v-model="item.member.nickname" :customStyle="customStyle02" trim placeholder="请输入发布者称呼" />
					</uv-form-item>
					
					<uv-form-item prop="member.weixin">
						<uv-input v-model="item.member.weixin" :customStyle="customStyle02" trim placeholder="请输入微信号" />
					</uv-form-item>
					
					<uv-form-item prop="member.qq">
						<uv-input v-model="item.member.qq" :customStyle="customStyle02" trim placeholder="请输入QQ号（选填）" />
					</uv-form-item>
				</view>
				
				<uv-button type="warning" form-type="submit" @click="submit" :loading="submitLoading" shape="circle" :ripple="true" :customStyle="customStyle04">提交</uv-button>
			</uv-form>
			
			<uv-datetime-picker ref="datetimePicker" v-model="item.datetime" mode="datetime" :maxDate="maxDate" @confirm="datetimePickerConfirm"></uv-datetime-picker>
		</view>
		
		<!--页面加载动画-->
		<rfLoading isFullScreen :active="loading"></rfLoading>
		<!-- <rf-back-top :scrollTop="scrollTop"></rf-back-top> -->
		<!-- <rf-back-home></rf-back-home> -->
	</view>
</template>

<script>
import { petMyView, petForm, fileImages, fileVideos } from '@/api/core';

const QQMapWX = require('@/common/qqmap-wx-jssdk.min.js');

export default {
	data() {
		return {
			qqmapsdk: null,
			$mData: this.$mData,
			hasLogin: false,
			userInfo: {},
			errorType: ['toast', 'message', 'borderBottom'],
			submitLoading: false,
			fileListVideo: [],
			fileListImage: [],
			loading: true,
			id: 0,
			item: {
				title: '',
				type: 1,
				cate: 1,
				nickname: '',
				age: 1,
				gender: 0,
				mode: 0,
				money: '0.00',
				refund_condition: '',
				vaccine: 0,
				sterilize: 0,
				deworm: 0,
				source: 1,
				size: 1,
				hair: 1,
				tags: [],
				requirements: [],
				other_requirement: '',
				address: '',
				content: '',
				images: [],
				video: '',
				datetime: 0,
				datetime_name: '',
				contact: {
					nickname: '',
					weixin: '',
					qq: ''
				},
				member: {
					nickname: '',
					weixin: '',
					qqq: ''
				}
			},
			maxDate: Number(new Date()),
			rules01: {
				images: this.$mData.rules.images,
				title: this.$mData.rules.title,
				nickname: this.$mData.rules.nickname,
				breed: this.$mData.rules.breed,
				money: this.$mData.rules.money,
				refund_condition: this.$mData.rules.refund_condition,
				other_requirement: this.$mData.rules.other_requirement,
				address: this.$mData.rules.address,
				content: this.$mData.rules.content,
				'member.nickname': this.$mData.rules['member.nickname'],
				'member.weixin': this.$mData.rules['member.weixin'],
				'member.qq': this.$mData.rules['member.qq']
			},
			rules02: {
				images: this.$mData.rules.images,
				title: this.$mData.rules.title,
				nickname: this.$mData.rules.nickname,
				breed: this.$mData.rules.breed,
				money: this.$mData.rules.money,
				datetime_name: this.$mData.rules.datetime_name,
				address: this.$mData.rules.address,
				content: this.$mData.rules.content,
				'member.nickname': this.$mData.rules['member.nickname'],
				'member.weixin': this.$mData.rules['member.weixin'],
				'member.qq': this.$mData.rules['member.qq']
			},
			rules03: {
				images: this.$mData.rules.images,
				title: this.$mData.rules.title,
				breed: this.$mData.rules.breed,
				money: this.$mData.rules.money,
				datetime_name: this.$mData.rules.datetime_name,
				address: this.$mData.rules.address,
				content: this.$mData.rules.content,
				'member.nickname': this.$mData.rules['member.nickname'],
				'member.weixin': this.$mData.rules['member.weixin'],
				'member.qq': this.$mData.rules['member.qq']
			}
		};
	},
	onLoad(option) {
		this.id = option.id ? option.id : this.id;
		this.qqmapsdk = new QQMapWX({
			key: this.$mData.maps[0].key
		});
	},
	onShow() {
		this.initLogin();
	},
	onReady(res) {
		if (this.id) {
			uni.setNavigationBarTitle({
			  title: '编辑领养'
			});
		} else {
			this.loading = false;
		}

		this.$refs.uvForm.setRules(this.rules01);
	},
	mounted() {
		this.initData();
	},
	computed: {
		rules() {
			return this[`rules0${this.item.type}`];
		},
		labelStyle() {
			return {
				height: '30rpx',
				fontSize: '30rpx',
				borderLeft: `6rpx ${this.themeColor.color} solid`,
				borderRadius: '3rpx',
				paddingLeft: '20rpx',
				margin: '0 0 20rpx 0'
			}
		},
		labelStyle02() {
			return {
				color: '#999',
				fontSize: '24rpx',
			}
		},
		labelStyle03() {
			return Object.assign(this.labelStyle, { marginBottom: '20rpx' });
		},
		customStyle01() {
			return { 
				borderRadius: '16rpx',
				padding: '20rpx 30rpx',
				marginTop: '20rpx'
			}
		},
		customStyle02() {
			return {
				color: '#333',
				fontSize: '28rpx',
				background: '#F6F7FB',
				border: 'none',
			}
		},
		customStyle04() {
			return {
				background: this.themeColor.color,
				color: '#FFF',
				fontSize: '30rpx',
				borderColor: this.themeColor.color,
				padding: '46rpx 0',
				marginTop: '60rpx'
			}
		}
	},
	watch: {
		'item.type'(val) {
			uni.setStorageSync('item', this.item);
			this.$refs.uvForm.resetFields();
			let item = uni.getStorageSync('item');
			this.item = item;
			this.$refs.uvForm.setRules(this.rules);
		}
	},
	methods: {
		async initLogin() {
			this.hasLogin = this.$mStore.getters.hasLogin;
			this.userInfo = uni.getStorageSync('userInfo');
			
			if (this.hasLogin && this.userInfo) {
				this.item.member.nickname = this.userInfo.nickname;
				this.item.member.weixin = this.userInfo.weixin;
				this.item.member.qq = this.userInfo.qq;
			} else {
				this.navTo('/pages/public/logintype');
			}
		},
		async initData() {
			if (this.id) {
				await this.getView();
			}
		},
		navTo(route) {
			this.$mRouter.push({ route });
		},
		typeSectionChange(index) {
			this.item.type = this.$mData.types[index].key;
		},
		cateSectionChange(index) {
			this.item.cate = this.$mData.cates[index].key;
		},
		genderSectionChange(index) {
			this.item.gender = this.$mData.genders[index].key;
		},
		ageSectionChange(index) {
			this.item.age = this.$mData.ages[index].key;
		},
		modeSectionChange(index) {
			this.item.mode = this.$mData.modes[index].key;
			if (this.item.mode == 0) this.item.money = '0.00';
		},
		vaccineSectionChange(index) {
			this.item.vaccine = this.$mData.vaccines[index].key;
		},
		sterilizeSectionChange(index) {
			this.item.sterilize = this.$mData.sterilizes[index].key;
		},
		dewormSectionChange(index) {
			this.item.deworm = this.$mData.deworms[index].key;
		},
		sourceSectionChange(index) {
			this.item.source = this.$mData.sources[index].key;
		},
		sizeSectionChange(index) {
			this.item.size = this.$mData.sizes[index].key;
		},
		hairSectionChange(index) {
			this.item.hair = this.$mData.hairs[index].key;
		},
		tagsCheckboxGroupChange(e) {
			//this.item.tags = e;
			this.$set(this.item, 'tags', e); //解决不及时更新的问题
		},
		tagsCheckboxChange(detail) {

		},
		requirementsCheckboxGroupChange(e) {
			//this.item.requirements = e;
			this.$set(this.item, 'requirements', e); //解决不及时更新的问题
		},
		requirementsCheckboxChange(detail) {
		
		},
		datetimePickerShow() {
			this.item.datetime = this.item.datetime ? this.item.datetime : Number(new Date());
			this.$refs.datetimePicker.open();
		},
		datetimePickerConfirm(e) {
			this.item.datetime_name = uni.$uv.timeFormat(e.value, 'yyyy-mm-dd hh:MM');
		},
		chooseLocation() {
			let _this = this;
			//#ifdef MP
			uni.authorize({
				scope: 'scope.userLocation',
				success(res) {
			//#endif
					uni.chooseLocation({
						success(res) {
							_this.$set(_this.item, 'address', res.address); //解决不及时更新的问题
							//_this.item.address = res.address;
							_this.item.coords = { lat: res.latitude, lng: res.longitude}; //纬度&经度
							_this.item.location = res.name;
							
							_this.qqmapsdk.reverseGeocoder({
								location: {
									latitude: res.latitude,
									longitude: res.longitude
								},
								success(res) {
									_this.item.province_id = res.result.ad_info.adcode.substring(0, 2) * 10000;
									_this.item.city_id = res.result.ad_info.city_code - 156000000;
									_this.item.area_id = res.result.ad_info.adcode * 1;
									_this.item.province = res.result.ad_info.province;
									_this.item.city = res.result.ad_info.city;
									_this.item.area = res.result.ad_info.district;
								},
								fail(error) {
									console.error(error);
								}
							});
						},
						fail(error) {
							console.error(error);
						}
					});
			//#ifdef MP
				},
				fail() {
					uni.showModal({
						content: '位置信息授权才能选择',
						success(res) {
							if (res.confirm) {
								uni.openSetting({
								  success(res) {
								    //console.log(res.authSetting);
								  }
								});
							}
						}
					});
				}
			});
			//#endif
		},
		async getView() {
			await this.$http.get(`${petMyView}?expand=member`, {
				id: this.id
			}).then(async r => {
				this.loading = false;
				this.item = r.data;
				this.item.datetime = this.item.datetime * 1000;
				this.item.datetime_name = this.item.datetime > 0 ? this.$uv.timeFormat(this.item.datetime, 'yyyy-mm-dd hh:MM') : '';
				
				let images = [];
				
				this.item.images.forEach((image, index) => {
					images.push({ url: image });
				});
				
				this.fileListImage = images;
				this.fileListVideo[0] = this.item.video;

				this.$mData.tags.forEach((item, index) => {
					if (this.item.tags.includes(item.name)) {
						item.checked = true;
					}
				});
				
				this.$mData.requirements.forEach((item, index) => {
					if (this.item.requirements.includes(item.name)) {
						item.checked = true;
					}
				});
			}).catch(err => {
				this.loading = false;
			});
		},
		submit() {
			let images = [];
			let videos = [];
			
			this.fileListImage.forEach((item, index) => {
				images.push(item.url);
			});
			
			this.fileListVideo.forEach((item, index) => {
				this.item.video = item.url;
			});
			
			let tags = [];
			this.$mData.tags.forEach((item, index) => {
				if (item.checked) {
					tags.push(item.name);
				}
			});
			
			let requirements = [];
			this.$mData.requirements.forEach((item, index) => {
				if (item.checked) {
					requirements.push(item.name);
				}
			});
			
			this.item.images = images;
			this.item.tags = tags;
			this.item.requirements = requirements;
			this.item.datetime = Math.floor(this.item.datetime / 1000);
			this.item.contact = this.item.member;

			setTimeout(() =>{
			  this.$refs.uvForm.validate().then(res => {
			  	if (res) {
			  		this.postItem(this.item);
			  	}
			  });
			}, 300);
		},
		postItem(params) {
			this.submitLoading = true;
			let url = `${petForm}`;
			if (this.id) url += `?id=${this.id}`;
			
			this.$http.post(url, {
				...params,
			}).then(async r => {
				this.submitLoading = false;
				
				let _this = this;
				uni.showModal({
					content: '发布成功！可能需审核通过后显示。',
					showCancel: false,
					success(res) {
						if (res.confirm) {
							_this.$mRouter.back();
						}
					}
				});
			}).catch(err => {
				this.submitLoading = false;
			});
		},
		async afterRead(event) {
			// 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
			let lists = [].concat(event.file);
			let fileListLen = this[`fileList${event.name}`].length;
			let uploadUrl = this.$mConfig.baseUrl;
			
			switch (event.name){
				case 'Image':
					uploadUrl += fileImages;
					break;
				case 'Video':
					uploadUrl += fileVideos;
					break;
				default:
					break;
			}
			
			lists.map((item) => {
				this[`fileList${event.name}`].push({
					...item,
					status: 'uploading',
					message: '上传中'
				});
			});
			// 此写法可以避免使用老写法在VUE3中不更新
			// #ifdef VUE3
			this[`fileList${event.name}`] = this[`fileList${event.name}`].filter((item, index) => {
			  return index>=0
			});
			// #endif
		
			for (let i = 0; i < lists.length; i++) {
				const result = await this.uploadFilePromise(lists[i].url, uploadUrl);
				let item = this[`fileList${event.name}`][fileListLen];
				let res = JSON.parse(result);
				
				this[`fileList${event.name}`].splice(fileListLen, 1, Object.assign(item, {
					status: 'success',
					message: '',
					url: res.data.url
				}));
				
				fileListLen++;
			}
		},
		uploadFilePromise(url, uploadUrl) {
			return new Promise((resolve, reject) => {
				let a = uni.uploadFile({
					url: uploadUrl,
					filePath: url,
					name: 'file',
					formData: {},
					success: (res) => {
						setTimeout(() => {
							resolve(res.data);
						}, 1000);
					}
				});
			});
		},
		trash(event) {
			this[`fileList${event.name}`] = this[`fileList${event.name}`].filter((item,index) => {
			  return index != event.index
			})
		},
	}
};
</script>

<style lang="scss">
page {
	background: $color-white;
	
	.wrap {
		padding: 30rpx;
		
		.subwrap {
			background: $color-white;
			
			.uv-checkbox {
				margin-bottom: 20rpx;
			}
			
			.contact {
				background: #F6F7FB;
				border-radius: 16rpx;
				padding: 10rpx 30rpx;
			}

			.progress-tips {
				color: $uv-warning;
				font-size: 24rpx;
				padding: 10rpx;
			}
		}
	}
}
</style>
